<template>
  <div>
    <el-form :rules="rules" ref="form" label-width="110px" :model="editData">
      <el-form-item label="质押人类型" prop="gua_entity_type">
        <c-select
          v-model="editData.gua_entity_type"
          class="form-control-ml"
          placeholder="请选择质押人类型"
          :options="enumEntityType"
        ></c-select>
      </el-form-item>
      <el-form-item
        :label="
          isCommon
            ? '营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)'
            : '身份证头像页OCR识别(请上传清晰的图片，以确保识别准确性，非必填)'
        "
      >
        <upload-oss
          single-image
          :dir="dir"
          ref="intellUpload"
          accept="image/*"
          :file-name="0"
          :file-list="registerList"
          :on-change="registerChange"
          :on-complete="handleAttachComplete"
        ></upload-oss>
      </el-form-item>
      <el-form-item label="出质人" prop="gua_entity">
        <el-input
          v-model="editData.gua_entity"
          class="form-control-ml"
          placeholder="请输入出质人"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="gua_entity_mobile">
        <el-input
          v-model="editData.gua_entity_mobile"
          class="form-control-ml"
          placeholder="请输入联系电话"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="gua_entity_address">
        <el-input
          v-model="editData.gua_entity_address"
          class="form-control-ml"
          placeholder="请输入地址"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="法定代表人(负责人)"
        prop="gua_entity_corp"
        v-if="+editData.gua_entity_type === 1"
      >
        <el-input
          v-model="editData.gua_entity_corp"
          class="form-control-ml"
          placeholder="请输入法定代表人(负责人)"
        ></el-input>
      </el-form-item>
      <el-form-item label="证件号" prop="gua_entity_cert_no">
        <el-input
          v-model="editData.gua_entity_cert_no"
          class="form-control-ml"
          placeholder="请输入统一信用代码、身份证号"
        ></el-input>
      </el-form-item>
      <el-form-item label="签约地点" prop="sign_address">
        <el-input
          v-model="editData.sign_address"
          class="form-control-ml"
          placeholder="请输入签约地点"
        ></el-input>
      </el-form-item>
      <el-form-item label="合同共计">
        <el-input
          class="form-control-ml"
          v-model="editData.num_copes_lower"
          placeholder="合同共计"
          v-input-number="{ min: 0, fixed: 0 }"
        >
          <span slot="append">份</span>
        </el-input>
      </el-form-item>
      <el-form-item label="甲乙双方各执">
        <el-input
          class="form-control-ml"
          v-model="editData.num_copes_per_lower"
          placeholder="甲乙双方各执"
          v-input-number="{ min: 0, fixed: 0 }"
        >
          <span slot="append">份</span>
        </el-input>
      </el-form-item>

      <el-form-item label="权利质物清单">
        <el-button size="mini" @click="addList">
          <i class="fa fa-plus"></i>
          新增一行
        </el-button>
        <table
          style="line-height: 1.2rem"
          class="table table-bordered table-sm bg-white table-vertical-middle text-center"
        >
          <colgroup>
            <col width="5%" />
            <col width="20%" />
            <col width="20%" />
            <col width="19%" />
            <col width="15%" />
            <col width="15%" />
            <col width="6%" />
          </colgroup>
          <tr>
            <td>序号</td>
            <td>专利名称</td>
            <td>申请日</td>
            <td>颁证日</td>
            <td>有效期</td>
            <td>评估值</td>
            <td>操作</td>
          </tr>
          <tr v-for="(p, index) of listData" :key="index">
            <td>{{ index + 1 }}</td>
            <td class="input-td text-danger">
              <el-input v-model="p.gua_right_name" placeholder="专利名称"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.apply_date" placeholder="申请日"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.cert_date" placeholder="颁证日"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.valid_period" placeholder="有效期"></el-input>
            </td>
            <td class="input-td">
              <el-input v-model="p.gua_right_value" placeholder="评估值"></el-input>
            </td>
            <td>
              <el-button type="text" @click="deleteList(index)">
                <i class="fa fa-trash text-danger"></i>
              </el-button>
            </td>
          </tr>
        </table>
      </el-form-item>

      <el-form-item label="是否加盖公章" v-if="isSYSTEM || isRedo">
        <c-select
          class="form-control-ml"
          :options="{
            0: '不盖章(客户线下签约时选择)',
            1: '加盖公章',
          }"
          :number-key="true"
          v-model="signStatus"
        ></c-select>
      </el-form-item>

      <el-form-item>
        <el-button class="btn-long" type="primary" @click="submit" :loading="saveLoading">
          保存
        </el-button>
        <el-button class="btn-long" @click="beforeClose" :loading="saveLoading">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mobileValidator } from '@/common/plugins/validator'
import {
  idCardValidate,
  licenseValidate,
  nzhToMoney,
  nzhToNum,
  arrayFromString,
  arrayToString,
} from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'
import { getIdCard, getOrgInfo } from '@/credit/views/city/program/ocr/index'
export default {
  components: {},
  props: {
    tableId: { type: String, default: '' },
    isRedo: {
      // 是否合同重做，
      type: Boolean,
      default: false,
    },
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    const certNoValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (+this.editData.gua_entity_type === 1 && !licenseValidate(value)) {
        callback(new Error('错误的营业执照号，请重新输入'))
      } else if (+this.editData.gua_entity_type !== 1 && !idCardValidate(value)) {
        callback(new Error('错误的身份证号，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      enumEntityType,
      editData: {},
      listData: [{}, {}],
      loading: false,
      tableName: 'gua_contract',
      saveLoading: false,
      rules: {
        gua_entity_type: { required: true, message: '请选择质押人类型', trigger: 'change' },
        gua_entity: { required: true, message: '请输入出质人', trigger: 'blur' },
        gua_entity_address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        gua_entity_corp: { required: true, message: '请输入法定代表人(负责人)', trigger: 'blur' },
        sign_address: [{ required: true, message: '请输入签约地点', trigger: 'blur' }],
        gua_entity_mobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: mobileValidator, message: '请输入正确的电话号码', trigger: 'blur' },
        ],
        gua_entity_cert_no: [
          { required: true, message: '请输入身份证号/营业执照号', trigger: 'blur' },
          { validator: certNoValidator, trigger: 'blur' },
        ],
        pledge_register_no: [
          { required: true, message: '请输入营业执照号', trigger: 'blur' },
          { validator: this.registerNoValidator, trigger: 'blur' },
        ],
        pledge_register_capital: {
          required: true,
          message: '请输入公司注册资本',
          trigger: 'blur',
        },
        pledge_stock: { required: true, message: '请输入持股比例', trigger: 'blur' },
        pledge_funds: { required: true, message: '请输入出资额', trigger: 'blur' },
        pledge_equity: { required: true, message: '请输入本次出质股权', trigger: 'blur' },
        pledge_funds_cur: { required: true, message: '请输入本次出质额度', trigger: 'blur' },
      },
      registerList: [],
      signStatus: 1,
    }
  },
  computed: {
    ...mapGetters(['entrustContract', 'org']),
    queryId() {
      return this.relatedData.customer_related_id
    },
    dir() {
      return `credit/contract/pledge/intellectual/${this.queryId}`
    },
    isCommon() {
      return +this.editData.gua_entity_type === 1
    },
    isSYSTEM() {
      // 系统后台重做合同
      return this.org.orgClass === 'org_credit_sys'
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.init()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    registerChange(file) {
      if (!file || !file.raw) {
        return
      }
      this.ocrFile = file.raw
      this.loading = true
      if (this.isCommon) {
        getOrgInfo(this.ocrFile)
          .then(res => {
            const data = res?.data ?? {}
            this.editData.gua_entity_cert_no = data.reg_num || ''
            this.editData.gua_entity = data.name
            this.editData.gua_entity_corp = data.person
            this.editData.gua_entity_address = data.address
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        getIdCard(this.ocrFile, true)
          .then(res => {
            const data = res?.data ?? {}
            this.editData.gua_entity_cert_no = data.num || ''
            this.editData.gua_entity = data.name
            this.editData.gua_entity_address = data.address
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    getListData() {
      if (!this.tableId) {
        this.listData = [{}, {}]
        return
      }
      this.saveLoading = true
      this.$api
        .getData(
          this.$serviceName,
          'gua_property_right_list',
          { 'gua_contract_id.eq': this.tableId },
          { create_time: 'asc' }
        )
        .then(res => {
          this.listData = res?.data ?? [{}]
          this.addList()
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    deleteList(index) {
      if (this.listData.length < 2) {
        return this.$message.warning('最少需添加一个权利质物清单')
      }
      this.listData.splice(index, 1)
    },
    addList() {
      this.listData.push({})
    },
    init() {
      this.editData = {
        ...this.formData,
        gua_entity_type: this.formData.gua_entity_type || '2',
        gua_entity_cert_no: this.formData.gua_entity_cert_no || '',
        gua_entity: this.formData.gua_entity || '',
        gua_entity_corp: this.formData.gua_entity_corp || '',
        gua_entity_address: this.formData.gua_entity_address || '',
      }
      const attach = arrayFromString(this.formData.cert_attachment)
      this.registerList = attach.length ? [{ url: attach?.[0] ?? '' }] : []
      this.getListData()
    },
    idCardValidator(rule, value, callback) {
      if (value === '') {
        callback()
      } else if (!idCardValidate(value)) {
        callback(new Error('错误的身份证号，请重新输入'))
      } else {
        callback()
      }
    },
    getDateFormat(value) {
      if (!value) {
        return ''
      }
      const str = value.replace(/[^\d]/g, '/')
      return new Date(str)
    },
    handleBeforeSave(model) {
      model.gua_entity = model.gua_entity?.replace(/\s*/g, '')
      model.gua_entity_corp = model.gua_entity_corp?.replace(/\s*/g, '')
      model.pledge_funds_capital = nzhToMoney(model.pledge_funds * 10000)
      model.num_copes_per = model.num_copes_per_lower ? nzhToNum(model.num_copes_per_lower) : ''
      model.num_copes = model.num_copes_lower ? nzhToNum(model.num_copes_lower) : ''
      model.customer_name = this.relatedData.customer_name
      model.customer_address = this.relatedData.address
      model.customer_phone = this.relatedData.mobile_no
      model.bank_name = this.entrustContract.bank_name
      model.entrust_bank_name = this.entrustContract.entrust_bank_name
      model.apply_funds = this.entrustContract.reply_funds
      model.loan_contract_no = this.entrustContract.loan_contract_no
      model.ensure_contract_no = this.entrustContract.ensure_contract_no
      model.gua_com_corp = this.entrustContract.accept_entrust_entity_corp
      model.customer_related_id = this.queryId
      model.gua_method = 2
      model.gua_method_sub = 2
      return model
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const slaveData = []
          for (let p of this.listData) {
            if (p.gua_right_name) {
              if (!p.apply_date) {
                return this.$message.warning(`请输入专利${p.gua_right_name}的申请日`)
              }
              if (!p.cert_date) {
                return this.$message.warning(`请输入专利${p.gua_right_name}的颁证日`)
              }
              if (!p.valid_period) {
                return this.$message.warning(`请输入专利${p.gua_right_name}的有效期`)
              }
              if (!p.gua_right_value) {
                return this.$message.warning(`请输入专利${p.gua_right_name}的评估值`)
              }
              slaveData.push(p)
            }
          }
          if (slaveData.length < 1) {
            return this.$message.warning('最少需添加一个权利质物清单')
          }
          this.$refs.intellUpload.submit()
        } else {
          this.$message.error('输入错误，请重新输入！')
        }
      })
    },
    handleAttachComplete(files) {
      this.editData.cert_attachment = arrayToString(files.map(it => it.url))
      this.updateList()
    },
    updateList() {
      const slaveData = []
      for (let p of this.listData) {
        if (p.gua_right_name) {
          if (!p.apply_date) {
            return this.$message.warning(`请输入专利${p.gua_right_name}的申请日`)
          }
          if (!p.cert_date) {
            return this.$message.warning(`请输入专利${p.gua_right_name}的颁证日`)
          }
          if (!p.valid_period) {
            return this.$message.warning(`请输入专利${p.gua_right_name}的有效期`)
          }
          if (!p.gua_right_value) {
            return this.$message.warning(`请输入专利${p.gua_right_name}的评估值`)
          }

          if (this.tableId) {
            p.gua_contract_id = this.tableId
          }
          slaveData.push(p)
        }
      }
      if (slaveData.length < 1) {
        return this.$message.warning('最少需添加一个权利质物清单')
      }
      const data = this.handleBeforeSave(this.editData)
      if (this.isSYSTEM || this.isRedo) {
        //系统后台重做重签合同
        data.sign_status = this.signStatus
        data.re_sign_type = this.tableId ? 1 : 2
      }
      data.sign_date = this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
      const formData = {
        masterTableInfo: JSON.stringify(data),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'gua_property_right_list',
      }
      if (this.tableId) {
        this.saveLoading = true
        this.$api
          .relatedUpdate(this.$serviceName, formData)
          .then(() => {
            this.handleSuccess()
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.saveLoading = true
        this.$api
          .relatedBatch(this.$serviceName, formData)
          .then(() => {
            this.handleSuccess()
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    handleSuccess() {
      this.init()
      this.$emit('success', true)
      this.$message.success('保存成功')
    },
    beforeClose() {
      this.$refs.form.clearValidate()
      this.$emit('close', false)
    },
  },
}
</script>

<style lang="scss" scoped>
.input-td {
  background: #ffffee;
}
</style>
